let treeUtils = module.exports = {};
// get all group from root group
/**
 * get all nodes
 * @param root must be mongoose path tree document
 * @param cb
 */
treeUtils.getAllNodes = function getAllNodes(root, cb) {

    if (!root) {
        return;
    }
    let results = [];
    root.getChildrenTree(function (err, nodes) {
        if (err) {
            cb(err, null);
            return;
        }
        // push first id
        results.push({
            id: root._id.toString(),
            name: root.name
        });
        for (let i = 0; i < nodes.length; i++) {
            if (nodes[i].isDelete) {
                // node is deleted
                continue;
            }
            results.push({
                id: nodes[i]._id.toString(),
                name: nodes[i].name
            });
            getAllGroupRecursive(nodes[i], results);
        }

        cb(null, results);
    });

};

function getAllGroupRecursive(node, recursiveResults) {
    // recursiveResults.push(node._id.toString());
    for (let i = 0; i < node.children.length; i++) {
        if (node.children[i].isDelete) {
            // node is deleted
            continue;
        }
        recursiveResults.push({
            id: node.children[i]._id.toString(),
            name: node.children[i].name
        });
        if (node.children[i].children.length > 0) {
            getAllGroupRecursive(node.children[i], recursiveResults);
        }
    }
}


treeUtils.tree2Array = function getAllNodes(tree) {
    if (!tree) {
        return;
    }
    let results = [];
    tree2ArrayRecursive(tree, results);
    return results;
};

function tree2ArrayRecursive(node, recursiveResults) {
    if (node.isDelete) {
        return;
    }
    recursiveResults.push(node);
    if (!node.children) {
        return;
    }
    for (let i = 0; i < node.children.length; i++) {
        if (node.children[i].isDelete) {
            // node is deleted
            continue;
        }
        recursiveResults.push(node.children[i]);
        if (node.children[i].children.length > 0) {
            tree2ArrayRecursive(node.children[i], recursiveResults);
        }
    }
}